<?php

namespace App\Http\Controllers\Admin\Blog;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Blog\Gallery;

class GalleryController extends Controller
{
    public function __construct()
    {
        view()->share([
            '_blog' => 'active open',
            '_gallery' => 'active',
        ]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $where = function ($query) use ($request) {
            //按相册主题
            if ($request->has('type') and $request->type != '-1') {
                $query->where('type', $request->type);
            }
        };

        $galleries = Gallery::where($where)->orderBy('created_at', 'desc')->get();
        return view('admin.blog.gallery.index', compact('galleries'));
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:galleries|max:45',
            'description' => 'required',
            'image' => 'required',
        ]);
        Gallery::create($request->all());
        return redirect(route('blog.gallery.index'))->with('success', '新增相册成功');
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $gallery = Gallery::find($id);
        return view('admin.blog.gallery.edit', compact('gallery'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required|max:45',
            'description' => 'required',
            'image' => 'required',
        ]);

        $gallery = Gallery::find($id);
        $gallery->update($request->all());
        return redirect(route('blog.gallery.index'))->with('success', '编辑相册成功');
    }

    /**
     * ajax删除相册
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (!Gallery::check_photo($id)) {
            return back()->with('error', '该相册里面有照片，请先删除照片~');
        }
        Gallery::destroy($id);
    }
}
